package org.coderfun.fieldmeta.auth;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.coderfun.common.exception.AppException;
import org.coderfun.fieldmeta.common.SystemCode;
import org.coderfun.member.core.SimpleMember;
import org.coderfun.member.core.entity.Member;
import org.coderfun.member.core.exception.MemberErrorCode;
import org.coderfun.member.core.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service("authService")
public class AuthServiceImpl implements AuthService{

	@Autowired
	MemberService memberService;
	
	@Autowired
	HttpSession session;
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	
	@Override
	public void login(String email, String plainPassword) {
		// TODO Auto-generated method stub
		Member member = memberService.getByEmail(email);
		
		if(null == member){
			throw new AppException(MemberErrorCode.USER_NOT_EXIST);
		}
		
		if((member.getLocked()!=null) && member.getLocked().equals(SystemCode.YES)){
			throw new AppException(MemberErrorCode.LOGIN_FORBIDDEN);
		}
		
		member.setPlainPassword(plainPassword);
		if(memberService.checkPassword(member)){
			SimpleMember simpleMember = new SimpleMember();
			try {
				BeanUtils.copyProperties(simpleMember, member);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
			session.setAttribute(MEMBER_ATTRIBUTE_NAME, simpleMember);
		}else{
			throw new AppException(MemberErrorCode.LOGIN_FAILED);
		}
	}

	@Override
	public void logout() {
		// TODO Auto-generated method stub
		session.removeAttribute(MEMBER_ATTRIBUTE_NAME);
		//session 失效
		session.invalidate();
	}

	@Override
	public SimpleMember getMember() {
		// TODO Auto-generated method stub
		return (SimpleMember) session.getAttribute(MEMBER_ATTRIBUTE_NAME);
	}

	@Override
	public Long getMemberId() {
		// TODO Auto-generated method stub
		return getMember().getId();
	}
	
	@Override
	public Long getWorkspaceId() {
		// TODO Auto-generated method stub
		String key = getWorkspaceKey();
		return Long.valueOf(redisTemplate.opsForValue().get(key));
	}	
	
	private String getWorkspaceKey(){
		Long memberId = getMemberId();
		return WORKSPACE_KEY_PREFIX + memberId;
	}

	@Override
	public void changeWorkspace(Long workspaceId) {
		// TODO Auto-generated method stub
		redisTemplate.opsForValue().set(getWorkspaceKey(), String.valueOf(workspaceId));
	}
}
